package org.gwu.seuss.server.command;

import java.util.ArrayList;
import java.util.List;

import org.gwu.seuss.communication.domain.FileTO;
import org.gwu.seuss.communication.request.Actions;
import org.gwu.seuss.communication.request.ClientRequest;
import org.gwu.seuss.communication.request.ServerResponse;
import org.gwu.seuss.domain.File;
import org.gwu.seuss.domain.User;

/**
 * 
 * @author mmoran
 *
 */
public class ListFilesCommand extends UserCommandBase implements Command {

	public ListFilesCommand(ClientRequest req) {
		super(req);
	}
	
	@Override
	public ServerResponse execute() throws Exception {
		userService.actionAllowed(req.getUsername(), Actions.LIST);
		log.info("User " +  req.getUsername() + "requested to get list of files.");
		
		// Obtain the user id for username
		User user = userService.selectUserByEmail(req.getUsername());
		
		ServerResponse rep = new ServerResponse();
		if(user != null) {
			List<File> files = fileService.selectAllFileByOwner(user.getUserId());
			List<FileTO> toFiles = new ArrayList<>(files.size());
			
			for(File file: files) {
				FileTO to = new FileTO();
				to.setFileId(file.getFileId());
				to.setFilename(file.getFilename());
				toFiles.add(to);
			}
			
			rep.setFiles(toFiles);
			rep.setSuccess(true);
			rep.setMessage("List of files owned by user");
			log.info("Returning the list of files owned by " + req.getUsername());
		} else {
			rep.setMessage("User not found: " + req.getUsername());
			log.error("User not found: " + req.getUsername());
		}
		
		return rep;
	}
}